package com.zahb.qadx.ui.adapter;

import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;


import com.chad.library.adapter.base.entity.node.BaseNode;
import com.chad.library.adapter.base.provider.BaseNodeProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.Curriculum;
import com.zahb.qadx.model.CurriculumChapter;
import com.zahb.qadx.model.MaterialInfo;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.CurriculumDetailsActivity;
import com.zahb.qadx.ui.activity.topic.DailyPracticeActivity;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.Tips;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;
import static com.zahb.qadx.ui.activity.CurriculumDetailsActivity.TYPE_FROM_TASK;

/**
 * Created by Zdw on 2020/10/21 16:29
 * 课程目录树末级
 */
public class ChapterProviderEnd extends BaseNodeProvider {

    @Override
    public int getItemViewType() {
        return 2;
    }

    @Override
    public int getLayoutId() {
        return R.layout.item_list_chapter_end;
    }

    @Override
    public void convert(@NotNull BaseViewHolder baseViewHolder, BaseNode baseNode) {
        if (baseNode instanceof CurriculumChapter) {
            CurriculumChapter chapter = (CurriculumChapter) baseNode;
            baseViewHolder.setText(R.id.tv_title, chapter.getName());
            if (getAdapter() instanceof ChapterAdapter) {
                ChapterAdapter chapterAdapter = (ChapterAdapter) getAdapter();
                if (chapter == chapterAdapter.getCurriculumChapter()) {
                    baseViewHolder.setTextColorRes(R.id.tv_title, R.color.blue_409eff);
                } else {
                    baseViewHolder.setTextColorRes(R.id.tv_title, R.color.gray_909399);
                }
                if (TextUtils.equals(chapter.getMaterialType(), "1")) {// 视频
                    baseViewHolder.setImageResource(R.id.iv_icon, R.drawable.ic_media_play);
                } else if (TextUtils.equals(chapter.getMaterialType(), "2")) {// 音频
                    baseViewHolder.setImageResource(R.id.iv_icon, R.drawable.ic_curriculum_audio);
                } else if (TextUtils.equals(chapter.getMaterialType(), "3")) {// 图书
                    baseViewHolder.setImageResource(R.id.iv_icon, R.drawable.ic_curriculum_book);
                } else {// 练习
                    baseViewHolder.setImageResource(R.id.iv_icon, R.drawable.ic_curriculum_practice);
                }
            }
        }
    }

    @Override
    public void onClick(@NotNull BaseViewHolder helper, @NotNull View view, BaseNode data, int position) {
        if (data instanceof CurriculumChapter) {
            CurriculumChapter chapter = (CurriculumChapter) data;
            if (!TextUtils.equals(chapter.getMaterialType(), "4")) {// 非练习
                if (view.getContext() instanceof BaseActivity) {
                    if (getAdapter() instanceof ChapterAdapter) {
                        ChapterAdapter chapterAdapter = (ChapterAdapter) getAdapter();
                        if (chapter == chapterAdapter.getCurriculumChapter()) return;
                        getMaterialInfo((BaseActivity) view.getContext(), chapter, chapterAdapter);
                    }
                }
            } else {// 练习
                /*if (TextUtils.isDigitsOnly(chapter.getMaterialId())) {
                    int practiceId = Integer.parseInt(chapter.getMaterialId());
                    MyPracticeActivity.actionStart(view.getContext(), chapter.getName(), practiceId);
                }*/
                try {

                    String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
                    String url = WebViewHelper.getBaseUrl() + "practice?practiceId=" + chapter.getMaterialId() + "&fromType=1&token=" + token;

//                    MyWebViewActivity.actionStart(view.getContext(), url, "", 1);
                    if (view.getContext() instanceof CurriculumDetailsActivity) {
                        CurriculumDetailsActivity activity = (CurriculumDetailsActivity) view.getContext();

                        // TODO: 2021/6/18   原生试题 梁尔宾
                        SharedPreferences settingss = view.getContext().getSharedPreferences("tryToSwitch", 0);
                        int isAmazing = settingss.getInt("tryToSwitch", 0);

                        String json=   tojson(1,1, activity.mCurriculum,chapter,activity.relationshipId);

                        if (isAmazing == 2) {
                            Intent intent = new Intent(view.getContext(), DailyPracticeActivity.class);
                            intent.putExtra("practiceId", chapter.getMaterialId());
                            intent.putExtra("path", 2);
                            intent.putExtra("json", json);
                            startActivity(intent);
                        } else {
                            MyWebViewActivity.actionStart(view.getContext(), url, "", 1);
                        }
                    }



                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void getMaterialInfo(BaseActivity activity, CurriculumChapter chapter, ChapterAdapter adapter) {
        activity.addDisposable(RetrofitService.getNetService()
                .getMaterialInfo(chapter.getMaterialSnapshotId())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        adapter.setPreCurriculumChapter(adapter.getCurriculumChapter());
                        adapter.setCurriculumChapter(chapter);
                        adapter.notifyDataSetChanged();
                        LiveEventBus.get(Constant.KEY_VIDEO_ID, MaterialInfo.class).post(response.getData());
                    } else {
                        activity.showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(activity);
                }));
    }
    private static final Gson mGson = new Gson();
    //封装的请求json
    public static String tojson(int actorType, int objType, Curriculum mCurriculum,  CurriculumChapter chapter,String  relationshipId) {

        Map<String, Object> params = new HashMap<>();
        Map<String, Object> actor = new HashMap<>();
        actor.put("actorId", BaseApplication.getContext().getDataLogin().getUser().getId());
        actor.put("actorType", BaseApplication.getContext().getDataLogin().getUser().getUserName());
        actor.put("actorName", actorType);
        Map<String, Object> extensions = new HashMap<>();
        extensions.put("rootOrgId", BaseApplication.getContext().getDataLogin().getCurrentOrg());
        extensions.put("organizationId", BaseApplication.getContext().getDataLogin().getCurrentOrg());
        actor.put("extensions", extensions);
        params.put("actor", actor);

        Map<String, Object> objectInfo = new HashMap<>();
        objectInfo.put("objType", objType);
        params.put("objectInfo", objectInfo);

        Map<String, Object> verbInfo = new HashMap<>();
        verbInfo.put("verbType","4" );
        Map<String, Object> extensions3 = new HashMap<>();
        verbInfo.put("extensions", extensions3);
        params.put("verbInfo", verbInfo);

        Map<String, Object> context = new HashMap<>();
        Map<String, Object> extensions1 = new HashMap<>();
        params.put("context", context);
        context.put("terminalInfo","APP");
        context.put("terminalType","2");
        extensions1.put("courseId", mCurriculum.getId());
        extensions1.put("courseOutlineId", chapter.getId());
        extensions1.put("courseSnapshotId", mCurriculum.getSnapshotId());
        extensions1.put("materialType", chapter.getMaterialType());
        extensions1.put("userCourseId", mCurriculum.getCourseUserId());
        extensions1.put("learnHours", chapter.getPeriod());
        extensions1.put("relationshipType", mCurriculum.getRelationshipType());
        extensions1.put("relationshipId", relationshipId);
        context.put("extensions", extensions1);
        params.put("context", context);


        Map<String, Object> extensions2 = new HashMap<>();
        extensions2.put("objIdType", 0);// 0:素材快照id,1:素材id
        String objId = chapter.getMaterialSnapshotId();
        if (TextUtils.isEmpty(objId)) {
            extensions2.put("objIdType", 1);
            objId = chapter.getMaterialId();
        }
            extensions2.put("objIdType", 2);
            extensions2.put("source", 2);

        if (TextUtils.isEmpty(relationshipId)) {
            extensions2.put("relationshipId", relationshipId);
            extensions2.put("relationshipType", "1");
        } else {
            extensions2.put("relationshipId", relationshipId);
            extensions2.put("relationshipType", 2);
        }

        objectInfo.put("extensions", extensions2);
        objectInfo.put("objSnapshotId", "");
        objectInfo.put("objId", objId);
        params.put("objectInfo", objectInfo);

        System.currentTimeMillis();
        params.put("actionTimestamp",  System.currentTimeMillis());
        Log.e("ttttttt", mGson.toJson(params));
        return mGson.toJson(params);

    }
}
